package com.gaofans.nrpc.example;

import com.gaofans.nrpc.common.context.ContextRequest;
import com.gaofans.nrpc.common.filter.FilterChain;
import com.gaofans.nrpc.common.processor.RpcContext;
import com.gaofans.nrpc.common.protocol.RpcRequestBuilder;
import com.gaofans.nrpc.common.protocol.RpcResponse;
import com.gaofans.nrpc.example.dict.DictService;
import com.gaofans.nrpc.example.dict.DictServiceImpl;
import com.gaofans.nrpc.server.bootstrap.RpcServer;
import com.gaofans.nrpc.server.bootstrap.RpcServerBuilder;
import com.gaofans.nrpc.server.handler.ServerFilter;
import reactor.core.publisher.Mono;

import javax.net.ssl.SSLException;

import static com.gaofans.nrpc.example.ClientApplication.buildServerSSL;

public class ServerApplication {

    public static void main(String[] args) throws Exception {
        buildServer(8080);
        buildServer(8081);
        buildServer(8082);
        buildServer(8083);
        Thread.currentThread().join();
    }



    private static void buildServer(int port) throws SSLException {
        RpcServer server = new RpcServerBuilder().port(port).sslContext(buildServerSSL()).build();
        server.registerService(DictService.class,new DictServiceImpl());
        server.addFilter((request, chain) -> {
            if ("123456".equals(request.header("token"))){
                RpcContext.current().set("token",Thread.currentThread().getName());
                return chain.doFilter(request);
            }else {
                chain.context().writeErrorResponse("token不正确");
                return Mono.error(new IllegalStateException("token 不正确"));
            }
        });
        server.start().subscribe();
    }


}
